// pages/my-inquiries/my-inquiries.ts
import { getMyInquiryList } from '../../../api/publish';
import { PAGES, goToPage } from '../../../config/pages.js';
import { formatDate } from '../../../utils/time';

Page({
  data: {
    searchValue: '',
    inquiries: [] as any[],
    loading: false,
    page: 1,
    limit: 20,
    hasMore: true,
    // 筛选条件
    selectedType: '', // all, processing, material, inventory
  },

  onLoad() {
    this.loadInquiries();
  },

  onShow() {
    // 刷新数据
    this.loadInquiries(true);
  },

  // 页面滚动到底部时触发
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadInquiries();
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadInquiries(true).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载我的询价列表
  async loadInquiries(refresh: boolean = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        page: 1,
        inquiries: [],
        hasMore: true
      });
    }

    this.setData({ loading: true });

    try {
      const params: any = {
        page: this.data.page,
        limit: this.data.limit
      };

      // 添加筛选条件
      if (this.data.selectedType && this.data.selectedType !== 'all') {
        params.type = this.data.selectedType;
      }
      // 添加搜索关键词
      if (this.data.searchValue) {
        params.keyword = this.data.searchValue;
      }

      const res = await getMyInquiryList(params);
      
      if (res.status === 200 && res.data) {
        // 格式化日期
        const formattedList = res.data.list.map((item: any) => ({
          ...item,
          formatted_date: formatDate(item.add_time || item.create_time),
          // 添加类型标签
          type_label: this.getTypeLabel(item.publish?.type),
          type_class: this.getTypeClass(item.publish?.type)
        }));
        
        const newInquiries = refresh ? formattedList : [...this.data.inquiries, ...formattedList];
        
        this.setData({
          inquiries: newInquiries,
          hasMore: newInquiries.length < (res.data.count || 0),
          page: this.data.page + 1
        });
      }
    } catch (error) {
      console.error('加载我的询价列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },


  // 搜索输入
  onSearchInput(e: any) {
    this.setData({
      searchValue: e.detail.value
    });
  },

  // 执行搜索
  performSearch(e: any) {
    // 如果是事件对象，获取输入值；如果是字符串，直接使用
    const keyword = typeof e === 'string' ? e : (e.detail?.value || '');
    this.setData({
      searchValue: keyword
    });
    this.loadInquiries(true);
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      searchValue: ''
    });
    this.loadInquiries(true);
  },

  // 跳转到详情页
  goToDetail(e: any) {
    const { id, type } = e.currentTarget.dataset;
    if (!id || !type) {
      wx.showToast({ title: '数据异常', icon: 'none' });
      return;
    }

    // 根据类型跳转到对应的详情页（与搜索结果页保持一致）
    switch (type) {
      case 'demand':
        goToPage(PAGES.DEMAND_DETAIL, { id });
        break;
      case 'inventory':
        goToPage(PAGES.BULK_MATERIAL_DETAIL, { id });
        break;
      case 'material':
      case 'processing':
        goToPage(PAGES.PRODUCT_DETAIL, { id });
        break;
      case 'group':
        goToPage(PAGES.GROUP_DETAIL, { id });
        break;
      default:
        wx.showToast({
          title: '未知的单据类型',
          icon: 'none'
        });
    }
  },

  // 获取类型标签
  getTypeLabel(type: string): string {
    const typeMap: any = {
      'group': '拼单',
      'demand': '求购',
      'processing': '加工',
      'material': '材料',
      'inventory': '散料'
    };
    return typeMap[type] || type;
  },

  // 获取类型样式类
  getTypeClass(type: string): string {
    const classMap: any = {
      'group': 'type-group',
      'demand': 'type-demand',
      'processing': 'type-processing',
      'material': 'type-material',
      'inventory': 'type-inventory'
    };
    return classMap[type] || 'type-default';
  },

  // 显示类型筛选弹窗
  showTypeModal() {
    const types = ['全部分类', '加工', '材料', '散料'];
    wx.showActionSheet({
      itemList: types,
      success: (res) => {
        const typeValues = ['all', 'processing', 'material', 'inventory'];
        this.setData({
          selectedType: typeValues[res.tapIndex],
          page: 1,
          inquiries: [],
          hasMore: true
        });
        this.loadInquiries();
      }
    });
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  }
});

